package com.gws.juc;

import java.util.concurrent.Semaphore;import java.util.concurrent.TimeUnit;
import javax.print.attribute.standard.Finishings;



/**
 * 3个空车位，6个人抢
 * @author gws
 *
 */
public class SemaphoreDemo {
	public static void main(String[] args) {
		Semaphore semaphore = new Semaphore(3);//模拟资源类，有3个空车位
		
		for (int i = 1; i <= 6; i++) {
			new Thread(() -> {
				try {
					semaphore.acquire();
					System.out.println(Thread.currentThread().getName()+"\t抢到了车位");
					//模拟实际项目中
					TimeUnit.SECONDS.sleep(2);
					System.out.println(Thread.currentThread().getName()+"\t离开了车位");
				} catch (Exception e) {
					e.printStackTrace();
				} finally{
					semaphore.release();
				}
			}, String.valueOf(i)).start();
		}
	}

}
